#include"Dlistnode.h"

DLnode* Listinit()
{
	DLnode* Dlist = Buynode(-1);
	Dlist->next = Dlist->prev = Dlist;
	return Dlist;
}

DLnode* Buynode(Nodedate x)
{
	DLnode* newnode = (DLnode*)malloc(sizeof(DLnode));
	newnode->next = NULL;
	newnode->prev = NULL;
	newnode->x = x;
	return newnode;
}

void DLprint1(DLnode* phead)
{
	assert(phead && phead->next != phead);
	DLnode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d->", cur->x);
		cur = cur->next;
	}
	printf("\n");
}

void DLprint2(DLnode* phead)
{
	assert(phead && phead->prev != phead);
	DLnode* cur = phead->prev;
	while (cur != phead)
	{
		printf("%d->", cur->x);
		cur = cur->prev;
	}
	printf("\n");
}

void pushback(DLnode* phead, Nodedate x)
{
	assert(phead);
	DLnode* newnode = Buynode(x);
	DLnode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}

void pushfront(DLnode* phead, Nodedate x)
{
	assert(phead);
	DLnode* newnode = Buynode(x);
	DLnode* next = phead->next;
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = next;
	next->prev = newnode;
}

void popback(DLnode* phead)
{
	assert(phead && phead->prev != phead);
	DLnode* tail = phead->prev;
	DLnode* newtail = tail->prev;
	free(tail);
	phead->prev = newtail;
	newtail->next = phead;
}

void popfront(DLnode* phead)
{
	assert(phead && phead->next != phead);
	DLnode* next = phead->next;
	DLnode* newnext = next->next;
	free(next);
	phead->next = newnext;
	newnext->prev = phead;
}

DLnode* Search(DLnode* phead, int pos)
{
	assert(phead && phead->next != phead);
	assert(pos >= 1);
	DLnode* cur = phead;
	while (pos--)
	{
		cur = cur->next;
	}
	return cur;
}

void Insert(DLnode* phead, int pos, Nodedate x)
{
	assert(phead);
	DLnode* joint = Search(phead, pos);
	DLnode* prev = joint->prev;
	DLnode* newnode = Buynode(x);
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = joint;
	joint->prev = newnode;
}

void Erase(DLnode* phead, int pos)
{
	assert(phead && phead->next != phead);
	DLnode* joint = Search(phead, pos);
	DLnode* prev = joint->prev;
	DLnode* next = joint->next;
	free(joint);
	prev->next = next;
	next->prev = prev;
}
